<?php

declare(strict_types=1);

namespace Service\LayoutService;

use App\Model\BbcModel\Layout;
use App\Model\BbcModel\Mnuser;
use Hyperf\DbConnection\Db;
use Service\BaseService;
use Service\Code\Normal;
use Service\GoodsService\MnGoodsService;

class LayoutService extends BaseService
{
    /**
     * @param array $store_ids 店铺ID数组
     * @param [type] $layout_id 微页面ID
     * @return array
     */
    public function storeSetPage(array $store_ids, $layout_id)
    {
        if (count($store_ids) <= 0) {
            return Normal::returnCode(Normal::FAIL, '缺少店铺');
        }
        if (empty($layout_id)) {
            return Normal::returnCode(Normal::FAIL, '缺少微页面ID');
        }
        $layout_info = Layout::instance()->info(['id' => $layout_id]);
        if (empty($layout_info)) {
            return Normal::returnCode(Normal::FAIL, '微页面不存在');
        }
        $mn_user_list = Mnuser::instance()
            ->where('id', 'in', $store_ids)
            ->get()->toArray();
        $mn_user_list_map = array_column($mn_user_list, null, 'id');

        //获取微页面组件商品ID
        $goods_ids = $this->getTemplateGoods($layout_info['content']);
        Db::startTrans();
        try {
            if (count($goods_ids) > 0) {
                foreach ($store_ids as $v) {
                    $mid = $mn_user_list_map[$v]['mid'] ?? '';
                    //验证商品是否存在于店铺
                    $res = MnGoodsService::instance()->checkGoods($v, $mid, $goods_ids);
                    if (!$res) {
                        throw new \Exception('店铺商品写入失败');
                    }
                }
            }
            Mnuser::instance()
                ->where('id', 'in', $store_ids)
                ->update(['layout_id' => $layout_id, 'md' => time()]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return Normal::returnCode(Normal::FAIL, $e->getMessage());
        }
        return Normal::returnCode(Normal::SUC, '设置成功');
    }

    /**
     * 获取模板商品ID数组（专题馆，商品分组，品牌馆）
     * @param [type] $content
     * @return array
     */
    public function getTemplateGoods($content)
    {
        if (empty($content)) {
            return [];
        }
        $content_arr = json_decode($content, true);
        $content_data = $content_arr['content'];

        $subject_ids    = [];
        $brandGroup_ids = [];
        $goodsGroup_ids = [];
        foreach ($content_data as $val) {
            //专题馆数据
            if ($val['type'] == 'subject') {
                $sub_entry = $val['setStyle']['sub_entry'] ?? [];
                if (count($sub_entry) > 0) {
                    $ids = array_column($sub_entry, 'id');
                    $subject_ids = array_merge($subject_ids, $ids);
                }
            }

            //品牌馆数据
            if ($val['type'] == 'brandGroup') {
                $sub_entry = $val['setStyle']['sub_entry'] ?? [];
                if (count($sub_entry) > 0) {
                    $ids = array_column($sub_entry, 'id');
                    $brandGroup_ids = array_merge($subject_ids, $ids);
                }
            }

            //商品分组数据
            if ($val['type'] == 'goodsGroup') {
                $sub_entry = $val['setStyle']['sub_entry'] ?? [];
                if (count($sub_entry) > 0) {
                    $ids = array_column($sub_entry, 'id');
                    $goodsGroup_ids = array_merge($subject_ids, $ids);
                }
            }
        }
        $goods_ids = [];
        if ($subject_ids) {
            $special_goods_list = Db::table('ly_specialtopic s')
                ->leftJoin('ly_specialtopic_goods sg', 'sg.specialtopic_id=s.id')
                ->leftJoin('ly_goods g', 'g.id=sg.goods_id')
                ->where('s.id', 'in', $subject_ids)
                ->where(['s.df' => 0, 's.status' => 1, 'g.df' => 0, 'g.status' => 1, 'sg.df' => 0])
                ->column('g.id');
            $goods_ids = array_merge($goods_ids, $special_goods_list);
        }

        if ($brandGroup_ids) {
            $brand_goods_list = Db::table('ly_goods g')
                ->where('brand_id', 'in', $brandGroup_ids)
                ->where(['df' => 0, 'status' => 1])
                ->column('id');
            $goods_ids = array_merge($goods_ids, $brand_goods_list);
        }

        if ($goodsGroup_ids) {
            $goodsGroup_goods_list = Db::table('ly_goods_group')
                ->where('id', 'in', $goodsGroup_ids)
                ->where(['df' => 0, 'status' => 1])
                ->where('goods_ids', '<>', '')
                ->column('goods_ids');

            $goods_group_list = explode(',', implode(',', $goodsGroup_goods_list));
            $goods_ids = array_merge($goods_ids, $goods_group_list);
        }

        $goods_ids = array_map('intval', $goods_ids);

        $new_goods_ids = array_unique($goods_ids);
        return $new_goods_ids;
    }
}
